<template>
  <div class="machine-page">
    <h1>机器信息</h1>
    <el-tabs v-model="activeTab">
      <!-- 将底部分页组件移动到机器管理tab内部 -->
      <el-tab-pane label="机器管理" name="machine">
        <el-card>
          <template #header>
            <div class="flex-between">
              <span>机器信息</span>
              <div>
                <el-input 
                  v-model="searchMachineId" 
                  placeholder="输入机器ID搜索" 
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter="searchMachineById"
                />
                <el-input 
                  v-model="searchMachineTypeId" 
                  placeholder="输入机器类型ID搜索" 
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter="searchMachineByTypeId"
                />
                <el-button type="primary" @click="searchMachineById">搜索机器</el-button>
                <el-button type="primary" @click="searchMachineByTypeId">搜索类型</el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button type="primary" @click="fetchIdleMachines">获取空闲机器</el-button>
                <el-button type="primary" @click="handleAdd">添加机器</el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="machines">
            <el-table-column prop="id" label="机器ID" width="120" sortable />
            <el-table-column prop="name" label="机器名称" sortable />
            <el-table-column prop="typeId" label="机器类型ID" width="120" sortable />
            <el-table-column prop="maxCapacity" label="最大产能(件/小时)" width="150" sortable />
            <el-table-column prop="status" label="状态" width="120" sortable>
              <template #default="scope">
                <el-tag :type="scope.row.status === '空闲' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" sortable />
            <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteMachine(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
      v-if="!isViewingIdleMachines"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next, jumper" background
      :total="pagination.total"
      style="margin-top: 20px; text-align: left">
    </el-pagination>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="机器类型管理" name="type">
        <el-card>
          <template #header>
            <div class="flex-between">
              <span>机器类型</span>
              <div>
                <el-input 
                  v-model="searchMachineTypeId" 
                  placeholder="输入机器类型ID搜索" 
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter="searchTypeById"
                />
                <el-button type="primary" @click="searchTypeById">搜索类型</el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button type="primary" @click="showTypeDialog = true">添加类型</el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="machineTypes">
                    <el-table-column prop="id" label="类型ID" width="120" sortable />
        <el-table-column prop="name" label="类型名称" sortable />
        <el-table-column prop="description" label="类型描述" sortable />
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="handleEditType(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteType(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-if="activeTab === 'type'"
            @size-change="handleTypeSizeChange"
            @current-change="handleTypeCurrentChange"
            :current-page="typePagination.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="typePagination.pageSize"
            layout="total, prev, pager, next, jumper" background
            :total="typePagination.total">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 机器类型对话框 -->
    <el-dialog v-model="showTypeDialog" :title="isEditType ? '编辑机器类型' : '添加机器类型'">
      <el-form :model="typeFormData" label-width="120px">
        <el-form-item label="类型ID" v-if="isEditType">
          <el-input v-model="typeFormData.id" disabled/>
        </el-form-item>
        <el-form-item label="类型名称">
          <el-input v-model="typeFormData.name"/>
        </el-form-item>
        <el-form-item label="类型描述">
          <el-input v-model="typeFormData.description" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTypeDialog = false">取消</el-button>
        <el-button type="primary" @click="saveType">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showDialog" :title="dialogTitle">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="机器ID" v-if="isEdit">
          <el-input v-model="formData.id" disabled/>
        </el-form-item>
        <el-form-item label="机器名称">
          <el-input v-model="formData.name"/>
        </el-form-item>
        <el-form-item label="机器类型ID">
          <el-input v-model="formData.typeId"/>
        </el-form-item>
        <el-form-item label="最大产能">
          <el-input-number v-model="formData.maxCapacity" :min="0"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status">
            <el-option label="空闲" value="空闲"/>
            <el-option label="生产中" value="生产中"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMachine">保存</el-button>
      </template>
    </el-dialog>
    <!-- 在el-table下方添加分页组件 -->
    
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const machines = ref([
])

const showDialog = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')
const formData = ref({
  id: '',
  name: '',
  typeId: '',
  maxCapacity: 0,
  status: '空闲'
})
const activeTab = ref('machine')

// 添加获取机器类型的方法
const fetchMachineTypes = async () => {
  try {
    const response = await axios.post('http://117.72.45.141:8091/api/machine-type/page', {
      typeName: typeQueryParams.value.typeName,
      pageNum: typePagination.value.pageNum,
      pageSize: typePagination.value.pageSize
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.success) {
      machineTypes.value = response.data.data.records.map(item => ({
        id: item.machineTypeId,
        name: item.typeName,
        description: item.description,
        createTime: item.createTime
      }))
      typePagination.value.total = response.data.data.total
    }
  } catch (error) {
    console.error('获取机器类型列表出错:', error)
    ElMessage.error('获取机器类型列表失败')
  }
}

// 监听分页切换
watch(activeTab, (newTab) => {
  if (newTab === 'type') {
    fetchMachineTypes()
  }
})
const machineTypes = ref([
  {
    id: 'TYPE001',
    name: 'CNC车床',
    description: '数控车床类型',
    createTime: '2023-01-01 10:00'
  }
])
const typeFormData = ref({
  id: '',
  name: '',
  description: ''
})

const showTypeDialog = ref(false)
const isEditType = ref(false)

const handleEditType = (type) => {
  typeFormData.value = { ...type }
  isEditType.value = true
  showTypeDialog.value = true
}

const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加机器'
  // 重置表单数据
  formData.value = {
    id: '',
    name: '',
    typeId: '',
    maxCapacity: 0,
    status: '空闲'
  }
  showDialog.value = true
}
const handleDeleteType = async (type) => {
  try {
    const response = await axios.delete(`http://117.72.45.141:8091/api/machine-type/${type.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      ElMessage.success('机器类型删除成功');
      const index = machineTypes.value.findIndex(t => t.id === type.id);
      if (index !== -1) {
        machineTypes.value.splice(index, 1);
      }
      fetchMachineTypes(); // 刷新机器类型列表
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除失败，请检查网络连接');
    console.error('删除机器类型出错:', error);
  }
}

const saveType = async () => {
  try {
    // 检查名称是否已存在
    const isNameExist = await checkTypeName(
      typeFormData.value.name,
      isEditType.value ? typeFormData.value.id : ''
    );
    console.log('检查机器类型名称结果:', {
  name: typeFormData.value.name,
  excludeId: isEditType.value ? typeFormData.value.id : '',
  isNameExist: isNameExist
});
    if (!isNameExist) {
      ElMessage.error('机器类型名称已存在，请使用其他名称');
      return;
    }

    const method = isEditType.value ? 'PUT' : 'POST';
    const response = await axios({
      method,
      url: 'http://117.72.45.141:8091/api/machine-type',
      data: {
        typeName: typeFormData.value.name,
        description: typeFormData.value.description,
        machineTypeId: isEditType.value ? typeFormData.value.id : undefined
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      ElMessage.success(isEditType.value ? '机器类型更新成功' : '机器类型添加成功');
      showTypeDialog.value = false;
      fetchMachineTypes(); // 刷新机器类型列表
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败，请检查网络连接');
    console.error('保存机器类型出错:', error);
  }
}


const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑机器'
  formData.value = {
    id: row.id,
    name: row.name,
    typeId: row.typeId,
    maxCapacity: row.maxCapacity,
    status: row.status
  }
  showDialog.value = true
}

const handleDeleteMachine = async (machine) => {
  try {
    const response = await axios.delete(`http://117.72.45.141:8091/api/machine/${machine.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      ElMessage.success('机器删除成功');
      const index = machines.value.findIndex(m => m.id === machine.id);
      if (index !== -1) {
        machines.value.splice(index, 1);
      }
      fetchMachines(); // 刷新机器列表
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除失败，请检查网络连接');
    console.error('删除机器出错:', error);
  }
}

const saveMachine = async () => {
  try {
    // 添加调试日志查看实际返回值
    console.log('检查名称前:', formData.value.name, isEdit.value ? formData.value.id : '');
    
    const isNameAvailable = await checkMachineName(
      formData.value.name, 
      isEdit.value ? formData.value.id : ''
    );
    
    
    
    if (isNameAvailable) {
      ElMessage.error('机器名称已存在，请使用其他名称');
      return;
    }

    const method = isEdit.value ? 'PUT' : 'POST';
    const url = 'http://117.72.45.141:8091/api/machine';
    const response = await axios({
      method,
      url,
      data: {
        machineId: isEdit.value ? formData.value.id : undefined,
        machineName: formData.value.name,
        machineTypeId: formData.value.typeId,
        maxCapacity: formData.value.maxCapacity,
        status: formData.value.status === '空闲' ? '空闲' : '生产中'
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '机器更新成功' : '机器添加成功');
      showDialog.value = false;
      fetchMachines();
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败，请检查网络连接');
    console.error('保存机器出错:', error);
  }
}

// 添加分页相关变量
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 添加机器类型分页变量
const typePagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 添加机器类型查询参数
const typeQueryParams = ref({
  typeName: ''
})

const queryParams = ref({
  machineName: '',
  machineTypeId: '',
  status: ''
})

// 添加获取机器列表的方法
const fetchMachines = async () => {
  try {
    const response = await axios.post('http://117.72.45.141:8091/api/machine/page', {
      machineName: queryParams.value.machineName,
      machineTypeId: queryParams.value.machineTypeId,
      status: queryParams.value.status,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.success) {
      machines.value = response.data.data.records.map(item => ({
        id: item.machineId,
        name: item.machineName,
        typeId: item.machineTypeId,
        typeName: item.typeName,
        maxCapacity: item.maxCapacity,
        status: item.status,
        createTime: item.createTime,
        updateTime: item.updateTime
      }))
      pagination.value.total = response.data.data.total
      pagination.value.current = response.data.data.current
      pagination.value.pages = response.data.data.pages
    } else {
      ElMessage.error(response.data.message || '获取机器列表失败')
    }
  } catch (error) {
    console.error('获取机器列表出错:', error)
    ElMessage.error('获取机器列表出错')
  }
}

// 监听分页变化
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val
  if (isViewingIdleMachines.value) {
    fetchIdleMachines()
  } else {
    fetchMachines()
  }
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  if (isViewingIdleMachines.value) {
    fetchIdleMachines()
  } else {
    fetchMachines()
  }
}

const handleTypeCurrentChange = (val) => {
  typePagination.value.pageNum = val
  fetchMachineTypes()
}

const handleTypeSizeChange = (val) => {
  typePagination.value.pageSize = val
  fetchMachineTypes()
}

// 初始化时获取数据
onMounted(() => {
  fetchMachines()
})

const searchMachineId = ref('')

const searchMachineById = async () => {
  if (!searchMachineId.value.trim()) {
    ElMessage.warning('请输入机器ID')
    return
  }

  try {
    const response = await axios.get(`http://117.72.45.141:8091/api/machine/${searchMachineId.value}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.code === 200) {
      const machine = response.data.data
      machines.value = [{
        id: machine.machineId,
        name: machine.machineName,
        typeId: machine.machineTypeId,
        typeName: machine.typeName,
        maxCapacity: machine.maxCapacity,
        status: machine.status,
        createTime: machine.createTime,
        updateTime: machine.updateTime
      }]
      pagination.value.total = 1
    } else {
      ElMessage.error(response.data.message || '未找到该机器')
    }
  } catch (error) {
    console.error('搜索机器出错:', error)
    ElMessage.error('搜索机器出错')
  }
}
const searchMachineTypeId = ref('')

const searchTypeById = async () => {
  if (!searchMachineTypeId.value.trim()) {
    ElMessage.warning('请输入机器类型ID')
    return
  }

  try {
    const response = await axios.get(`http://117.72.45.141:8091/api/machine-type/${searchMachineTypeId.value}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.code === 200) {
      const type = response.data.data
      machineTypes.value = [{
        id: type.machineTypeId,
        name: type.typeName,
        description: type.description,
        createTime: type.createTime
      }]
      typePagination.value.total = 1
    } else {
      ElMessage.error(response.data.message || '未找到该机器类型')
    }
  } catch (error) {
    console.error('搜索机器类型出错:', error)
    ElMessage.error('搜索机器类型出错')
  }
}

const resetSearch = () => {
  searchMachineId.value = ''
  searchMachineTypeId.value = ''
  isViewingIdleMachines.value = false
  fetchMachines()
}
const isViewingIdleMachines = ref(false)

const fetchIdleMachines = async () => {
  try {
    isViewingIdleMachines.value = true
    const response = await axios.get('http://117.72.45.141:8091/api/machine/idle', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.code === 200) {
      machines.value = response.data.data.map(item => ({
        id: item.machineId,
        name: item.machineName,
        typeId: item.machineTypeId,
        typeName: item.typeName,
        maxCapacity: item.maxCapacity,
        status: item.status,
        createTime: item.createTime,
        updateTime: item.updateTime
      }));
      pagination.value.total = response.data.data.length;
      isViewingIdleMachines.value = true;
      ElMessage.success(`获取到${response.data.data.length}台空闲机器`);
    } else {
      ElMessage.error(response.data.message || '获取空闲机器失败');
    }
  } catch (error) {
    console.error('获取空闲机器出错:', error)
    ElMessage.error('获取空闲机器出错')
  }
}
const checkTypeName = async (name, excludeId = '') => {
  try {
    const response = await axios.get('http://117.72.45.141:8091/api/machine-type/check-name', {
      params: {
        typeName: name,
        excludeId: excludeId
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      // 根据接口文档，data为true表示名称可用，false表示已存在
      return response.data.data === false; // 返回true表示名称已存在
    }
    return false;
  } catch (error) {
    console.error('检查机器类型名称出错:', error);
    return false;
  }
}
const checkMachineName = async (name, excludeId = '') => {
  try {
    const response = await axios.get('http://117.72.45.141:8091/api/machine/check-name', {
      params: {
        machineName: name,
        excludeId: excludeId
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      // 根据接口文档，data为true表示名称可用，false表示已存在
      return response.data.data === true;
    }
    return false;
  } catch (error) {
    console.error('检查机器名称出错:', error);
    return false;
  }
}
const searchMachineByTypeId = async () => {
  if (!searchMachineTypeId.value.trim()) {
    ElMessage.warning('请输入机器类型ID')
    return
  }

  try {
    const response = await axios.post('http://117.72.45.141:8091/api/machine/page', {
      machineTypeId: searchMachineTypeId.value,
      pageNum: 1,
      pageSize: pagination.value.pageSize
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.success) {
      machines.value = response.data.data.records.map(item => ({
        id: item.machineId,
        name: item.machineName,
        typeId: item.machineTypeId,
        typeName: item.typeName,
        maxCapacity: item.maxCapacity,
        status: item.status,
        createTime: item.createTime,
        updateTime: item.updateTime
      }))
      pagination.value.total = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取机器列表失败')
    }
  } catch (error) {
    console.error('根据类型ID搜索机器出错:', error)
    ElMessage.error('根据类型ID搜索机器出错')
  }
}
</script>

<style scoped>
.machine-page {
  padding: 20px;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
}
</style>